<?php

/*
 * B端操作功能模块
 * 功能：活动
 */

namespace Home\Controller;

use Think\B_Controller;

class ActionController extends B_Controller {
    
    CONST ROUGH_STATUS = 2;
    CONST RELEASE_STATUS = 1;
    CONST DELETE_STATUS=4;
    
    CONST PAY_PRICE = 100;//单位 分
    
    public function __construct() {
        parent::__construct();
        $this->a = D('Action','Logic');
    }
    
    public function index(){
        $type = (int)$_GET['type'];
        $store_id = (int)$_GET['store_id'];
        if(!in_array($store_id,$this->store_id)){
            $store_id = $this->store_id;
        }
        $actions = $this->a->getActionsByStoreId($store_id,$type);
        $o = D('Order','Logic');
        foreach($actions as $k=>$v){
            if($v['model_type']==2){
                $re = $this->a->getFaceNumByAction($v['id']);
            }elseif($v['model_type']==1){
                $re = $o->getActionOrderNumByActon($v['id']);
            }
            $actions[$k]['num'] = (int)$re['num'];
            //活动图
            $ids = json_decode($v['content'], true);
            if ($ids['ids']) {
                $img=array();
                $item = new \Home\Logic\ShopitemLogic();
                $items = $item->getItemsByIds(array_keys($ids['ids']), $v['store_id'], true);
                if(count($items[0]['images'])>0){
                    if(count($items[0]['images'])>1){
                        $img[] = $items[0]['images'][0]['image'];
                        $img[] = $items[0]['images'][1]['image'];
                    }else{
                        $img[] = $items[0]['images'][0]['image'];
                        $img[] = '/upload/action.jpg';
                    }   
                }else{
                    $img[] = '/upload/action.jpg';
                    $img[] = '/upload/action.jpg';
                }
                $actions[$k]['img'] =$img; 
            }




            if($v['status']==self::ROUGH_STATUS){
                $actions[$k]['status_name'] = '草稿';
            }else{
                $time = time();
                $actions[$k]['status_name'] = $v['end_time']>$time?'进行中':'结束';
            }
        }
        $this->assign('store_id',$store_id);
        $this->assign('type',$type);
        $this->assign('actions',$actions);
        $this->display('action');
    }
    
    public function append(){
        $start = (int)$_GET['start'];
        $type = (int)$_GET['type'];
        $store_id = (int)$_GET['store_id'];
        if(!in_array($store_id,$this->store_id)){
            $store_id = $this->store_id;
        }
        $o = D('Order','Logic');
        $actions = $this->a->getActionsByStoreId($store_id,$type,$start);
        foreach($actions as $k=>$v){
            $re = $o->getActionOrderNumByActon($v['id']);
            $actions[$k]['num'] = (int)$re['num'];

            //活动图
            $ids = json_decode($v['content'], true);
            if ($ids['ids']) {
                $img=array();
                $item = new \Home\Logic\ShopitemLogic();
                $items = $item->getItemsByIds(array_keys($ids['ids']), $v['store_id'], true);
                if(count($items[0]['images'])>0){
                    if(count($items[0]['images'])>1){
                        $img[] = $items[0]['images'][0]['image'];
                        $img[] = $items[0]['images'][1]['image'];
                    }else{
                        $img[] = $items[0]['images'][0]['image'];
                        $img[] = '/upload/action.jpg';
                    }   
                }else{
                    $img[] = '/upload/action.jpg';
                    $img[] = '/upload/action.jpg';
                }
                $actions[$k]['img'] =$img; 
            }

            if($v['status']==self::ROUGH_STATUS){
                $actions[$k]['status_name'] = '草稿';
            }else{
                $time = time();
                $actions[$k]['status_name'] = $v['end_time']>$time?'进行中':'结束';
            }
        }
        if(count($actions)>0){
            exit(json_encode($actions));
        }
        exit('false');
    }
    
    public function info(){
        $id = (int)$_GET['id'];
        $info = $this->a->getAction($id);
        if(!in_array($info['store_id'],$this->store_id)){
            $this->_msg('_HAVE_NO_LEGAL_POWER_');
        }
        if($info['status']==self::ROUGH_STATUS){
            redirect('/home/action/create?id='.$id);
        }else{
            if($info['model_type']==2){
                redirect('/home/action/detail?id='.$id);
            }
            redirect('/home/action/preview?id='.$id);
        }
    }

    /**
     * 活动 创建
     */
    public function create(){
        // 门店信息
        if ( empty($this->store) )
        {
            redirect('/home/store');
        }
        //表示该活动为复制
        if($_GET['copy']==1){
            $this->assign('copy',true);
        }
        if( $_GET['id']>0 )
        {
            $action_id = $_GET['id'];
            $actions = $this->a->getAction($action_id);
            $action_model_id = $actions['model_type'];
            if(!in_array($actions['store_id'],$this->store_id)){
                $this->_msg('_HAVE_NO_LEGAL_POWER_');
            }
            $actions['intro'] = str_replace('<br/>', "\n",$actions['intro']);
            $con = json_decode($actions['content'],true);
            if($con['ids']){  //增加商品模块后增加改段代码，为兼容之前版本
                $it = D('Shopitem','Logic');
                $_item = $it->getItemsByIds(array_keys($con['ids']),$actions['store_id']);
                $this->assign("_item",$_item);
            }
            $this->assign('actions',$actions);
            $b = D('Barber','Logic');
            $barber = $b->getBarberByStoreId($actions['store_id']);
            $this->assign('barber',$barber);
        }
        // 获取活动类型
        $action_type = $this->a->getMarketingModel();
        if ( $_GET['id']>0 )
        {
            foreach( $action_type as $k=>$v ){
                $action_type[$k]['intro'] = str_replace('<br/>', "\n",$v['intro']);
                $model_ids[] = $action_type[$k]['id'];
                $model_names[] = $action_type[$k]['link'];
                if ( $action_model_id && $action_model_id == $action_type[$k]['id'] ){
                    $action_link = $action_type[$k]['link'];
                }
            }
            $this->assign('action_type',$action_type);
        }
        else
        {
            foreach( $action_type as $k=>$v ){
                $action_type[$k]['intro'] = str_replace('<br/>', "\n",$v['intro']);
                $model_ids[] = $action_type[$k]['id'];
                $model_names[] = $action_type[$k]['link'];
            }
            $action_model_id = (int)trim($_GET['model_id'])?trim($_GET['model_id']):0;
            $action_link = trim( $_GET['model'] );
            $this->assign('action_type',$action_type);
        }
        // 确定访问
        if ( $action_model_id!=1  && $action_model_id!=0 && in_array( $action_model_id,$model_ids ) && in_array( $action_link,$model_names ))
        {
            $this->display( $action_link );die();
        }
        $this->display('create');
    }

    /**
     * 活动 提交数据
     */
    public function submit(){
        $data['store_id'] = (int)$_POST['store_id'];
        $data['barber_id'] = (int)$_POST['barber'];
        $data['action_name'] = $_POST['action_name'];
        $data['model_type'] = (int)$_POST['type'];
        $data['start_time'] = strtotime($_POST['start_time']);
        $data['end_time'] = strtotime($_POST['end_time'])+86399;
        $data['use_end_time'] = trim( $_POST['use_end_time'] )?strtotime($_POST['use_end_time'])+86399:strtotime($_POST['end_time'])+86399;
        if($_POST['logo'] != '/upload/crowd.png'){
            $data['logo'] = $_POST['logo']?str_replace('./','/',$_POST['logo']):'';
        }else{
            $data['logo'] = $_POST['logo'];
        }
        $data['intro'] = $_POST['intro'];
        $data['only'] = (int)$_POST['only'];
        $data['price'] = (int)$_POST['price'];
        if(strlen($data['action_name'])<1 
                || $data['start_time']==FALSE
                || $data['end_time']==FALSE
                || strlen($data['intro'])<1){
            $this->_msg('_SYSTEM_ERROR_');
        }
        if(!in_array($data['store_id'],$this->store_id)){
            $this->_msg('_HAVE_NO_LEGAL_POWER_');
        }
        if( $data['model_type']==2 ){
            $data['content'] = $this->contentFormates();
        }
        elseif ( $data['model_type']==3 )  //公益
        {
            $_content = $this->contentFormat();
            $crowd_name = trim( $_POST['crowd_name'] );
            $data['content'] = json_encode(array('ids'=>$_content['ids'],'crowd_name'=>$crowd_name));
            $data['price'] = $_content['price'];
        }
        else
        {
            $_content = $this->contentFormat();
            $data['content'] = json_encode(array('ids'=>$_content['ids']));
            $data['price'] = $_content['price'];
        }
        $data['create_time'] = time();
        $data['status'] = self::ROUGH_STATUS;
        $action_id = $this->a->insertAction($data);
        if($data['model_type']==2){
            $coupon = D('Coupon','Logic');
            $array=array('is_action'=>$action_id);
            if((int)$_POST['lf']){
                $coupon->updateHui((int)$_POST['lfCoupon_id'],$array);
            }
            if((int)$_POST['tr']){
                $coupon->updateHui((int)$_POST['trCoupon_id'],$array);
            }
            if((int)$_POST['xh']){
                $coupon->updateHui((int)$_POST['xhCoupon_id'],$array);
            }
            if((int)$_POST['wm']){
                $coupon->updateHui((int)$_POST['wmCoupon_id'],$array);
            }
            if($_POST['hp_con']){
                $coupon->updateHui((int)$_POST['hpCoupon_id'],$array);
            }
        }
        if(!$action_id){
            $this->_msg('_SYSTEM_ERROR_');
        }else{
            if($_POST['caogao'] == "保存草稿"){
                redirect('/home/action');
            }
        }
        redirect("/home/action/preview?id=$action_id");
    }

    /**
     * 活动 预览
     */
    public function preview(){
        $action_id = $_GET['id'];
        $action = $this->a->getAction($action_id); 
        if(!in_array($action['store_id'],$this->store_id)){
            $this->_msg('_HAVE_NO_LEGAL_POWER_');
        }
        if($action['model_type'] == 1){ //判断是否为拼团
            $ids = json_decode($action['content'],true);
            $item = D("Shopitem","Logic");
            $items = $item->getItemsByIds(array_keys($ids['ids']),$action['store_id'],true);
            foreach($items as $k=>$v){
                $items[$k]['real_price'] = $ids['ids'][$v['id']]/100;
                if($v['is_meal_set']==1){//如果是套餐取出其中包含的单品
                    $meal_set_items = $item->getItemByMealSetId($v['id'],$action['store_id'],true);
                }
                $items[$k]['meal_set_items'] = $meal_set_items;
            }
            $this->assign('items',$items);
        }elseif ( $action['model_type'] == 3 ){ // 判断是否是众筹
            $ids = json_decode($action['content'],true);
            $item = D("Shopitem","Logic");
            $items = $item->getItemsByIds(array_keys($ids['ids']),$action['store_id'],true);
            foreach($items as $k=>$v){
                $items[$k]['real_price'] = $ids['ids'][$v['id']]/100;
                if($v['is_meal_set']==1){//如果是套餐取出其中包含的单品
                    $meal_set_items = $item->getItemByMealSetId($v['id'],$action['store_id'],true);
                }
                $items[$k]['meal_set_items'] = $meal_set_items;
            }
            $this->assign('items',$items);
        }
        $store = $this->s->getStore($action['store_id']);
        $this->assign('store',$store);
        $this->assign('action',$action);

        if($action['model_type'] == 3){
            $this->display('preview_crowd');
        }else{
            $this->display('preview');
        }
        
    }

    public function detail(){
        //import('MsgCode', 'Msgcode');
        //$m = new \Msgcode\MsgCode();
        $_SESSION['s_verify'] = time();
        //$m->setSession($_SESSION);
        
        $action_id = $_GET['id'];
        $action = $this->a->getAction($action_id);
        if(in_array($action['store_id'], $this->store_id) ){
            $this->_msg('_HAVE_NO_LEGAL_POWER_');
        }
        $face = $this->a->getFaceByAction($action_id);
        $mobile = '';
        if($face){
            foreach ($face as $k => $v) {
                $mobile .=$v['mobile'].',';
            }
        }
        $end_time = $action['end_time'];
        $this->assign('end_time',$end_time);
        $this->assign('mobile',$mobile);
        $this->assign('face',$face);
        $this->display('detail');
    }

    /**
     * 活动 更新
     */
    public function update(){
        $data['id']=$_POST['id'];
        $info = $this->a->getAction($data['id']);
        if($data['id']<1 || !in_array($info['store_id'],$this->store_id)){
            $this->_msg('_HAVE_NO_LEGAL_POWER_');
        }
        $data['barber_id'] = (int)$_POST['barber'];
        $data['action_name'] = $_POST['action_name'];
        $data['model_type'] = (int)$_POST['type'];
        $data['start_time'] = strtotime($_POST['start_time']);
        $data['end_time'] = strtotime($_POST['end_time'])+86399;
        $data['use_end_time'] = trim( $_POST['use_end_time'] )?strtotime($_POST['use_end_time'])+86399:strtotime($_POST['end_time'])+86399;
        // $data['logo'] = $_POST['banner_logo'];
        if($_POST['logo'] != '/upload/crowd.png'){
            $data['logo'] = $_POST['logo']?str_replace('./','/',$_POST['logo']):'';
        }else{
            $data['logo'] = $_POST['logo'];
        }
        $data['intro'] = $_POST['intro'];
        $data['only'] = (int)$_POST['only'];
        $data['price'] = $_POST['price'];
        if($data['id']<1
                || strlen($data['action_name'])<1 
                || $data['start_time']==FALSE
                || $data['end_time']==FALSE
                // || strlen($data['logo'])<1
                || strlen($data['intro'])<1){
            $this->_msg('_SYSTEM_ERROR_');
        }


        $data['create_time'] = $info['create_time'];
        if($data['model_type']==2)
        {
            $data['content'] = $this->contentFormates();
        }
        elseif ( $data['model_type']==3 ) //公益
        {
            $_content = $this->contentFormat();
            $crowd_name = trim( $_POST['crowd_name'] );
            $crowd_name = trim( $_POST['crowd_name'] );
            $data['content'] = json_encode(array('ids'=>$_content['ids'],'crowd_name'=>$crowd_name));
            $data['price'] = $_content['price'];
        }
        else
        {
            $_content = $this->contentFormat();
            $data['content'] = json_encode(array('ids'=>$_content['ids']));
            $data['price'] = $_content['price'];
        }
        $data['status'] = self::ROUGH_STATUS;
        $action_id = $this->a->updateAction($data);
        if($data['model_type']==2){
            $coupon = D('Coupon','Logic');
            $array=array('is_action'=>$data['id']);
            if($_POST['lf']){
                $coupon->updateHui((int)$_POST['lfCoupon_id'],$array);
            }
            if($_POST['tr']){
                $coupon->updateHui((int)$_POST['trCoupon_id'],$array);
            }
            if($_POST['xh']){
                $coupon->updateHui((int)$_POST['xhCoupon_id'],$array);
            }
            if($_POST['wm']){
                 $coupon->updateHui((int)$_POST['wmCoupon_id'],$array);
            }
            if($_POST['hp_con']){
                 $coupon->updateHui((int)$_POST['hpCoupon_id'],$array);
            }
        }
        if($_POST['caogao'] == "保存草稿"){
            redirect('/home/action');
        }

        redirect("/home/action/preview?id=".$data['id']);
    }

    public function delete(){
        $id = (int)$_POST['id'];
        $info = $this->a->getAction($id);
        if($id<1 || !in_array($info['store_id'],$this->store_id)){
            $this->_msg('_HAVE_NO_LEGAL_POWER_');
        }
        if($this->a->updateActionStatus($id,self::DELETE_STATUS)==false){
            $this->_msg('_SYSTEM_ERROR_');
        }
        redirect('/home/action');
    }
    
    public function img(){
        layout(false);
        $this->display('img');
    }
    
    public function upload(){ 
        layout(false);
        import('Think.upload');
        $u = new \Think\Upload();
        $path = $u->upload($_FILES);
        $this->assign('path','/public/upload/'.$path['img']['savepath'].$path['img']['savename']);
        $this->display('img');
    }

    /**
     * 活动 发布
     */
    public function release(){
        $id = (int)$_GET['action_id'];
        $info = $this->a->getAction($id);
        if($info['status'] == 1){
            redirect('/home/action');
        }
        if($id<1 || !in_array($info['store_id'],$this->store_id)){
            $this->_msg('_HAVE_NO_LEGAL_POWER_');
        }

        if($this->a->updateActionStatus($id,self::RELEASE_STATUS)==false){
            $this->_msg('_SYSTEM_ERROR_');
        }
        redirect('/home/action');
    }

    private function contentFormat(){
        $_price = $_POST['real_price'];
        $_items = $_POST['items'];
        $ids = array();
        $tatal_price = 0;
        foreach($_items as $k=>$v){
            $price = $_price[$k];
            $price = (int)($price*100);
            $ids[$v] = $price;
            $tatal_price += $price;
        }
        return array('price'=>$tatal_price,'ids'=>$ids);
        
    }

    public function contentFormates(){
        $lf = trim($_POST['lf']);
        $tr = trim($_POST['tr']);
        $xh = trim($_POST['xh']);
        $wm = trim($_POST['wm']);
        $lf_con = trim($_POST['lf_con']);
        $tr_con = trim($_POST['tr_con']);
        $xh_con = trim($_POST['xh_con']);
        $wm_con = trim($_POST['wm_con']);
        $hp_con = trim($_POST['hp_con']);
        
        $key = array();
        $content = array();

        if(strlen($lf_con)>0){
            $key[] = $lf;
            $content["$lf"] = $lf_con;
        }
        if(strlen($tr_con)>0){
            $key[] = $tr;
            $content["$tr"] = $tr_con;
        }
        if(strlen($xh_con)>0){
            $key[] = $xh;
            $content["$xh"] = $xh_con;
        }
        if(strlen($wm_con)>0){
            $key[] = $wm;
            $content["$wm"] =$wm_con;
        }
        if(strlen($hp_con)>0){
            $key[] = 'help';
            $content["help"] =$hp_con;
        }

        return json_encode(array('key'=>$key,'content'=>$content));
    }
    
    public function getBarber(){
        $store_id = (int)$_GET['store_id'];
        if($store_id<1 || !in_array($store_id,$this->store_id)){
            exit('false');
        }
        $b = D('Barber','Logic');
        $barber = $b->getBarberByStoreId($store_id);
        echo json_encode($barber);
        exit;
    }

    public function sendMsg(){
        $mobile = $_GET['mobile'];
        $action_id = (int)$_GET['action_id'];
        $face = $this->a->getFaceByAction($action_id);
        $action = $this->a->getAction($action_id);
        if($face[0]['msg']==1){
            echo 2;
            exit;
        }
        $c = D('coupon','Logic');
        $coupons = $c->getCouponsByActionId($action_id);
        $s = D('store','Logic');
        $store = $s->getStore($coupons[0]['store_id']);
        if(!in_array($store['id'],$this->store_id)){
            $this->_msg('_HAVE_NO_LEGAL_POWER_');
        }
        $num = 0;
        if($face){
            foreach($coupons as $k => $v){
                for($i=1;$i<=$v['num'];$i++){
                    $l=$this->ling($face[$num]['mobile'],$v['id'],$face[$num]['barber_id'],$v['store_id']);
                    if($l==true){
                        $this->a->updateFaceMsg($face[$num]['id']);
                    }
                    $num++;
                }
            }
        }
        import('MsgCode', 'Msgcode');
        $m = new \Msgcode\MsgCode();
        $_contents = '2&1&'.$store['name'].'&'.$action['action_name'];
        $re = $m->sendMsg_b($mobile,$_contents,true);
        if($re){
            echo 1;
        }else{
            echo 0;
        }
        exit;
    }

    //领取优惠劵
    public function ling($mobile,$coupon_id,$barber_id,$store_id){
        $data['coupon_id'] = $coupon_id;
        $u = D('User','Logic');
        $user = $u->getUserByAccount($mobile);
        $data['client_id'] = $user['id'];
        $data['number'] = $this->code();
        $data['create_time'] = time();
        $data['store_id'] = $store_id;
        $data['barber_id'] = $barber_id;
        if($data['coupon_id']<1 ||
            $data['store_id']<1 ||
            $data['client_id']<1 ||
            $data['barber_id']<0){
            return false;
        }
        $c = D('Coupon','Logic');
        //领取
        $s = $c->count($data['coupon_id'],$data);
        if($s == false){
           return false;
       }
        if($s){   
           return true;
       }

    }
    //识别码
    public function code(){
        return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
    
    public function items(){
        $store_id = (int)$_GET['store_id'];
        $it = D('Shopitem','Logic');
        $item = $it->getItemsByStoreId($store_id,1);
        if(count($item)<1 || $item == false){
            exit('false');
        }
        echo json_encode($item);
        exit;
    }

    public function face( $action=false ){
        if($action!=false){
            $this->assign('actions',$action);
        }
        $this->display('faceCreate');
    }

    //删除活动
    public function deleteAction(){
        $id = (int)$_GET['id'];
        $store_id = (int)$_GET['store_id'];
        $info = $this->a->getAction($id);
        if($id<1 || !in_array($info['store_id'],$this->store_id)){
            $this->_msg('_HAVE_NO_LEGAL_POWER_');
        }
        $statu = 4;
        $re = $this->a->updateActionStatus($id,$statu);
        if($re){
            echo 1; //删除成功
        }else{
            echo 2; //删除失败
        }
    }

    public function qrcode(){
        $action_id = (int)$_GET['action_id'];
        $store_id = (int)$_GET['store_id'];
        if($action_id>0){
            include_once(APP_PATH . "Weixin/phpqrcode/phpqrcode.php");
            $errorCorrectionLevel = "L"; // 纠错级别：L、M、Q、H  
            $matrixPointSize = "4"; // 点的大小：1到10 
            $url = 'http://www.'._DOMAIN_ALL_.'/user/action/info?aid='.$action_id.'&store_id='.$store_id;
            //$url = 'http://www.mmvip.net/user/action/info?aid=197&store_id=24'; 
            \QRcode::png($url, false, $errorCorrectionLevel, $matrixPointSize);
            exit;
        }
    }

    
}
